<?php
/**
 * phpOffice的PhpSpreadsheet相关使用内容
 */
namespace util;

use PhpOffice\PhpSpreadsheet\Spreadsheet;

class Office
{
    /**
     * 导出Excel
     * @param  string $fileName 文件名称
     * @param  array  $headArr  Excel标题头数组 [['name'=>'标题1', 'width'=>20]] width默认可以没有
     * @param  array  $data     数据内容
     * @param  array  $options  自定义配置信息 ['width'=>15] 目前只有宽度，后续可以增加，可以设置默认宽度
     * @param  string $suffix   文件后缀，xlsx 和 xls
     * @return [type]           [description]
     */
    function exportExcel($fileName = '', $headArr = [], $data = [], $options = [], $suffix = 'xlsx')
    {
        @ini_set('memory_limit', '2048M');
        @set_time_limit(0);

        if (!$headArr || !$data || !is_array($data)) {
            return false;
        }

        $fileName   .= "_" . date("YmdHis");
        $spreadsheet = new Spreadsheet();
        $objPHPExcel = $spreadsheet->getActiveSheet();

        // 设置表头
        $colum = 'A';
        foreach ($headArr as $v) {
            $objPHPExcel->setCellValue($colum . '1', $v['name']);
            if (!empty($v['width'])) {
                $objPHPExcel->getColumnDimension($colum)->setWidth($v['width']);
            } elseif (!empty($options['width'])) {
                $objPHPExcel->getColumnDimension($colum)->setWidth($options['width']);
            }

            $colum++;
        }

        $column = 2;
        // 行写入
        foreach ($data as $key => $rows) {
            $span = 'A';
            // 列写入
            foreach ($rows as $keyName => $value) {
                $objPHPExcel->setCellValue($span . $column, $value);
                $span++;
            }
            $column++;
        }

        // 重命名表（UTF8编码不需要这一步）
        $fileName = iconv("utf-8", "gbk//IGNORE", $fileName);
        // 清理缓存
        ob_end_clean();

        if ($suffix == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $class = "\PhpOffice\PhpSpreadsheet\Writer\Xlsx";
        } elseif ($suffix == 'xls') {
            header('Content-Type:application/vnd.ms-excel');
            $class = "\PhpOffice\PhpSpreadsheet\Writer\Xls";
        }
        header('Content-Disposition: attachment;filename="' . $fileName . '.' . $suffix . '"');
        header('Cache-Control: max-age=0');

        $writer = new $class($spreadsheet);
        $writer->save('php://output');

        // 删除清空 释放内存
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);

        exit;
    }

    /**
     * 导出csv文件
     * @param  string $fileName 文件名称
     * @param  array  $headArr  Excel标题头数组
     * @param  array  $data     数据内容
     * @return [type]           [description]
     */
    public function exportCsv($fileName = '', $headArr = [], $data = [])
    {
        @ini_set('memory_limit', '2048M');
        @set_time_limit(0);
        if (!$headArr || !$data || !is_array($data)) {
            return false;
        }
        try {
            setlocale(LC_ALL, 'en_US.UTF-8');
            // 输出 Excel 文件头
            $fileName = empty($fileName) ? date('YmdHis') : $fileName . '_' . date('YmdHis');
            $fileName = $fileName . ".csv";
            $string   = "";
            $string  .= implode(',', $headArr) . "\n";//首先写入表格标题栏
            foreach ($data as $key => $value) {
                foreach ($value as $k => $val) {
                    $value[$k] = $val;
                }
                $string .= implode(",", $value) . "\n"; //用英文逗号分开
            }
            ob_end_clean();
            header("Content-type:text/csv");
            header("Content-Disposition:attachment;filename=" . $fileName);
            header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
            header('Expires:0');
            header('Pragma:public');
            echo iconv('UTF-8', 'GBK//IGNORE', $string);
            
            exit;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
    
}
